import { Command } from 'commander'
import chalk from 'chalk'
import { spawn } from 'child_process'

export const devCommand = new Command('dev')
  .description('Start development server')
  .option('-p, --port <port>', 'port number', '3000')
  .option('-h, --host <host>', 'host address', 'localhost')
  .option('-o, --open', 'open browser automatically')
  .action(async options => {
    try {
      console.log(chalk.blue('🚀 Starting development server...'))

      const args = ['dev']

      if (options.port) {
        args.push('--port', options.port)
      }

      if (options.host) {
        args.push('--host', options.host)
      }

      if (options.open) {
        args.push('--open')
      }

      console.log(chalk.gray(`Running: vite ${args.join(' ')}`))

      const devServer = spawn('vite', args, {
        stdio: 'inherit',
        cwd: process.cwd(),
        shell: true,
      })

      // Handle process termination
      process.on('SIGINT', () => {
        console.log(chalk.yellow('\n🛑 Shutting down development server...'))
        devServer.kill('SIGINT')
        process.exit(0)
      })

      process.on('SIGTERM', () => {
        devServer.kill('SIGTERM')
        process.exit(0)
      })

      devServer.on('error', error => {
        console.error(
          chalk.red('❌ Failed to start development server:'),
          error
        )
        process.exit(1)
      })

      devServer.on('exit', code => {
        if (code !== 0) {
          console.error(
            chalk.red(`❌ Development server exited with code ${code}`)
          )
          process.exit(code || 1)
        }
      })
    } catch (error) {
      console.error(chalk.red('❌ Error starting development server:'), error)
      process.exit(1)
    }
  })
